package com.zhou.core.scheduler.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程名字工厂类
 * Created by zhouyongjun on 2020/8/13
 */
public class ThreadNameFactory implements ThreadFactory {
    Logger logger;
    private String threadName;
    private ThreadGroup threadGroup;
    private AtomicInteger threadNumber;
    private boolean daemon;

    public ThreadNameFactory(String threadName) {
        this(threadName, false);
        this.threadName = threadName;
    }

    public ThreadNameFactory(String threadName, boolean daemon) {
        this.logger = LoggerFactory.getLogger(ThreadNameFactory.class);
        this.threadNumber = new AtomicInteger(0);
        this.threadName = threadName;
        this.daemon = daemon;
        SecurityManager s = System.getSecurityManager();
        this.threadGroup = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.threadName = threadName + "-thread-";
        this.daemon = daemon;
    }

    public Thread newThread(Runnable r) {
        Thread thread = new Thread(this.threadGroup, r, this.threadName + this.threadNumber.getAndIncrement(), 0L);
        if (this.daemon) {
            thread.setDaemon(this.daemon);
        } else {
            if (thread.isDaemon()) {
                thread.setDaemon(false);
            }

            if (thread.getPriority() != Thread.NORM_PRIORITY) {
                thread.setPriority(Thread.NORM_PRIORITY);
            }
        }

        if (this.logger.isDebugEnabled()) {
//            this.logger.debug("创建线程:" + this.threadName);
        }

        return thread;
    }

    public String getThreadName() {
        return this.threadName;
    }
}

